package com.five.taotao.login;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.five.taotao.Application.MyApplication;
import com.five.taotao.R;
import com.five.taotao.http.CallBack;
import com.five.taotao.util.VolleyUtil;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * gaomengjiao
 * Created by MQ on 2016/11/3.
 */
public class LoginActivity extends AppCompatActivity {

    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.usernameWrapper)
    TextInputLayout usernameWrapper;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.passwordWrapper)
    TextInputLayout passwordWrapper;
    @BindView(R.id.btn)
    Button btn;
    @BindView(R.id.forgetpwd)
    TextView forgetpwd;
    @BindView(R.id.register)
    TextView register;
    @BindView(R.id.thridLogin)
    TextView thridLogin;
    @BindView(R.id.back)
    ImageView back;

    private String passwords;
    private String phones;
    private LoginHelper loginHelper;//登录帮助类

    private Tencent mTencent;
    //appid
    private static String APP_ID = "1105729347";
    //获取权限列表。所有权限为 all
    private static String SCOPE = "all";
    //回调接口
    private IUiListener loginListener;
    private IUiListener userInfoListener;

    //   private IUiListener shareListener;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        usernameWrapper.setHint("手机号");//让浮动标签动起来
        passwordWrapper.setHint("密码");


        //添加监听
        phone.addTextChangedListener(new MyTextWatcher(phone));
        password.addTextChangedListener(new MyTextWatcher(password));
    }

    /**
     * 点击登录按钮
     */
    @OnClick(R.id.btn)
    public void onClick() {
        hideKeyboard();
        phones = usernameWrapper.getEditText().getText().toString();
        passwords = passwordWrapper.getEditText().getText().toString();
        if (!validatePhone() || !checkPhonePattern(phones)) {
            usernameWrapper.setError("请输入正确的手机号!");
        } else if (!validatePassword(passwords)) {
            passwordWrapper.setError("输入密码有误!");
        } else {
            usernameWrapper.setErrorEnabled(false);
            passwordWrapper.setErrorEnabled(false);
            doLogin();
        }
    }


    /**
     * 自动隐藏虚拟键盘
     */
    private void hideKeyboard() {
        View view = getCurrentFocus();
        if (view != null) {
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
                    hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 检测密码是否正确，   后期还会再改
     *
     * @param passwords 密码
     * @return 密码是否大于5位
     */
    public boolean validatePassword(String passwords) {
        return password.length() > 5;
    }

    //验证手机号的正则表达式
    private static final String PHONE_PATTERN = "[1][34578]\\d{9}";
    private Pattern pattern = Pattern.compile(PHONE_PATTERN);
    private Matcher matcher;

    /**
     * 检查输入的号码是否是手机号
     *
     * @param phones 输入的手机号
     * @return
     */
    public boolean checkPhonePattern(String phones) {
        matcher = pattern.matcher(phones);
        return matcher.matches();
    }

    /**
     * 动态输入过程中不再显示错误提醒
     *
     * @param
     * @return
     */
    public boolean validatePhone() {
        if (phone.getText().toString().trim().equals("") || phone.getText().toString().trim().isEmpty()) {
            usernameWrapper.setError("请输入正确的手机号!");
            phone.requestFocus();
            return false;
        }
        usernameWrapper.setErrorEnabled(false);
        return true;
    }

    //动态监听edittext输入过程
    private class MyTextWatcher implements TextWatcher {
        private View view;

        private MyTextWatcher(View view) {
            this.view = view;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            switch (view.getId()) {
                case R.id.phone:
                    validatePhone();
                    break;
                case R.id.password:
                    validatePassword(passwords);
            }
        }
    }

    /**
     * 登录
     */
    public void doLogin() {
        Toast.makeText(getApplicationContext(), "OK!", Toast.LENGTH_SHORT).show();
        // TODO: login procedure; not within the scope of this tutorial.
        loadLatast();
    }


    //下拉加载最新数据
    private void loadLatast() {

        VolleyUtil.Get("http://192.168.191.1:8080/taotao/servlet/LoginServlet?account=" + phones + "&pwd=" + passwords)
                .setCallBack(new MyCallBack())
                .build()
                .setPriority(Request.Priority.HIGH)
                .start();
        /*VolleyUtil.Get("http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=2&size=8&offset=0")
                .setCallBack(new MyCallBack())
                .build()
                .setPriority(Request.Priority.HIGH)
                .addRequestHeadrs("apikey", "4600fe45a7f631f4800368013fb1a76e")
                .start();*/
    }


    /**
     * 网络监听回调方法
     */
    private class MyCallBack implements CallBack {

        @Override
        public void onSuccess(String response) {
            MyApplication.toast.toastShow("请求成功" + response);
        }

        @Override
        public void onErrer(VolleyError error) {
            MyApplication.toast.toastShow("请求错误");
        }

    }

    @OnClick({R.id.forgetpwd, R.id.register, R.id.thridLogin,R.id.back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.forgetpwd:
                Intent intent = new Intent(this, ForgetPwdActivity.class);
                startActivity(intent);
                break;
            case R.id.register:
                Intent intent1 = new Intent(this, RegisterActivity.class);
                startActivity(intent1);
                break;
            case R.id.back:
               finish();
                break;
            case R.id.thridLogin:
                View view1 = LayoutInflater.from(this).inflate(R.layout.login_pop, null, false);
                final PopupWindow popupWindow = new PopupWindow(view1
                        , ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                view1.findViewById(R.id.img).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });
                //6.0以下点击popupWindow外边空白，popupWindow消失的操作
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                ColorDrawable colorDrawable = new ColorDrawable(0);
                popupWindow.setBackgroundDrawable(colorDrawable);

                //设置动画效果
                popupWindow.setAnimationStyle(R.style.pop_anim);
                popupWindow.showAtLocation(view1, Gravity.BOTTOM, 0, 0);

                view1.findViewById(R.id.qq).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        initQqLogin();//初始化QQ登录分享的需要的资源
                        qqLogin(v);
                    }
                });
                break;
        }
    }

    //初始化QQ登录分享的需要的资源
    private void initQqLogin() {
        mTencent = Tencent.createInstance(APP_ID, this);
        //创建QQ登录回调接口
        loginListener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
                //登录成功后回调该方法
//                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                //设置openid，如果不设置这一步的话无法获取用户信息
                JSONObject jo = (JSONObject) o;
                String openID;
                try {
                    openID = jo.getString("openid");
                    String accessToken = jo.getString("access_token");
                    String expires = jo.getString("expires_in");
                    mTencent.setOpenId(openID);
                    mTencent.setAccessToken(accessToken, expires);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(UiError uiError) {
                //登录失败后回调该方法
                Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                Log.e("LoginError:", uiError.toString());
            }

            @Override
            public void onCancel() {
                //取消登录后回调该方法
                Toast.makeText(LoginActivity.this, "取消登录", Toast.LENGTH_SHORT).show();
            }
        };
        //获取用户信息的回调接口
        userInfoListener = new IUiListener() {
            @Override
            public void onComplete(Object o) {
                JSONObject jo = (JSONObject) o;
                Log.e("COMPLETE:", jo.toString());
                try {
                    JSONObject info = (JSONObject) o;
                    Log.e("JO:", jo.toString());
                    String nickName = info.getString("nickname");
                    String gender = info.getString("gender");
                    String figureurl_qq_2 = info.getString("figureurl_qq_2");

                    SharedPreferences sp = getSharedPreferences("Login", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("nickName", "Hi~ ," + nickName).putString("figureUrl", figureurl_qq_2).commit();//写入本地文件数据

                    setResult(2, new Intent());
                    Toast.makeText(LoginActivity.this, "你好，" + nickName, Toast.LENGTH_LONG).show();
                    finish();//关闭当前Activtiy

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {

            }

        };
    }

    //qq登录功能
    public void qqLogin(View view) {
        mTencent.login(this, SCOPE, loginListener);
    }

    //获取用户信息
    private void getUserInfo() {
        UserInfo info = new UserInfo(this, mTencent.getQQToken());
        info.getUserInfo(userInfoListener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_LOGIN) {
            if (resultCode == -1) {
                Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
                Tencent.handleResultData(data, loginListener);
                getUserInfo();
            }
        }
    }
}
